<template>
  <div class="search-box">
    <div class="input-group">
      <el-input
          v-model="latitude"
          placeholder="纬度 (WGS84)"
          clearable
          @input="validateCoordinate('latitude')"
      />
      <el-input
          v-model="longitude"
          placeholder="经度 (WGS84)"
          clearable
          @input="validateCoordinate('longitude')"
      />
      <div class="button-group">
        <el-button
            type="primary"
            @click="handleSearch"
            :disabled="!isCoordinateValid"
            :loading="loading"
        >
          查询
        </el-button>
        <!-- 清空按钮 -->
        <el-button
            type="info"
            @click="clearInputs"
            :disabled="!latitude && !longitude && images.length === 0"
        >
          清空
        </el-button>
      </div>
    </div>
    <div class="image-display" v-if="images.length > 0">
      <div class="image-grid">
        <div v-for="(image, index) in images" :key="index" class="image-item">
          <img
              :src="image.url"
              alt="街景图像"
              class="street-view-image"
              @click="handleImageClick(image.url)"
          />
          <span class="image-label">{{ image.heading }}°</span>
        </div>
      </div>
      <el-button
          type="success"
          @click="downloadAllImages"
          class="download-btn"
      >
        下载全部
      </el-button>
    </div>
    <div class="no-image" v-else-if="searched && images.length === 0">
      无可用街景图像
    </div>
  </div>
</template>

<script>
import { ElInput, ElButton, ElMessage } from 'element-plus';
import {convertbc09llTobc09mm} from "../utils/baiduConvert.js";

export default {
  name: 'SearchBox',
  components: { ElInput, ElButton },
  emits: ['search'],
  data() {
    return {
      latitude: '',
      longitude: '',
      isCoordinateValid: false,
      images: [],
      searched: false,
      loading: false,
    };
  },
  methods: {
    validateCoordinate(type) {
      const lat = parseFloat(this.latitude);
      const lng = parseFloat(this.longitude);
      const isLatValid = !isNaN(lat) && lat >= -90 && lat <= 90;
      const isLngValid = !isNaN(lng) && lng >= -180 && lng <= 180;
      this.isCoordinateValid = isLatValid && isLngValid;
    },

    async handleSearch() {
      if (!this.isCoordinateValid) {
        ElMessage.warning('请输入有效的经纬度');
        return;
      }
      this.searched = true;
      this.images = [];
      this.$emit('search', {
        lat: parseFloat(this.latitude),
        lng: parseFloat(this.longitude)
      });
    },

    async fetchStreetViewImages(lng, lat) {
      this.loading = true;
      this.images = [];
      try {
        const panoId = await this.getPanoId(lng, lat);
        if (panoId) {
          const headings = [0, 90, 180, 270]; // 与 Python 脚本一致
          this.images = headings
              .map((heading) => ({
                heading,
                url: this.getStreetViewImageUrl(panoId, heading),
              }))
              .filter((image) => image.url); // 过滤无效 URL
          if (this.images.length > 0) {
            ElMessage.success('街景图像加载成功');
          } else {
            ElMessage.warning('该位置无街景数据');
          }
        } else {
          ElMessage.warning('该位置无街景数据');
        }
      } catch (error) {
        ElMessage.error('获取街景失败: ' + error.message);
        console.error('街景查询错误:', error);
      } finally {
        this.loading = false;
        this.searched = true;
      }
    },

    // 新增：清空输入框和图片显示
    clearInputs() {
      this.latitude = '';
      this.longitude = '';
      this.images = [];
      this.searched = false;
      ElMessage.info('输入框和街景图像已清空');
    },

    async getPanoId(lng, lat) {
      try {
        const data = await convertbc09llTobc09mm(lng, lat);
        console.log('百度经纬度转换结果：', data.lng, data.lat);
        const url = `https://mapsv0.bdimg.com/?&qt=qsdata&x=${data.lng}&y=${data.lat}&l=17.031000000000002&action=0&mode=day&t=${Date.now()}`;
        const response = await fetch(url, {
          headers: {
            'User-Agent': 'Mozilla/5.0 (Windows NT 11.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.6998.89 Safari/537.36',
            'Referer': 'https://map.baidu.com/',
            'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"',
            'sec-ch-ua-mobile': '?0',
          },
        });
        if (!response.ok) {
          console.error('API 响应状态:', response.status, response.statusText);
          throw new Error(`获取全景ID失败: ${response.statusText}`);
        }
        const text = await response.text(); // 确保 text 是字符串
        if (typeof text !== 'string' || text.trim() === '') {
          console.error('响应体为空或非字符串:', text);
          return null;
        }
        console.log('PanoId API 响应:', text); // 调试日志
        const reg = /"id":"(.+?)",/;
        const match = text.match(reg);
        if (!match) {
          console.error('正则匹配失败，未找到全景 ID');
          return null;
        }
        return match[1];
      } catch (error) {
        console.error('获取全景ID错误:', error);
        throw error;
      }
    },

    getStreetViewImageUrl(panoId, heading) {
      // 与 Python 脚本一致的图片 URL
      return `https://mapsv0.bdimg.com/?qt=pr3d&fovy=90&quality=100&panoid=${panoId}&heading=${heading}&pitch=0&width=1024&height=768`;
    },

    setCoordinates(lat, lng) {
      this.latitude = lat.toString();
      this.longitude = lng.toString();
      this.validateCoordinate('latitude');
      this.validateCoordinate('longitude');
    },

    handleImageClick(imageUrl) {
      window.open(imageUrl, '_blank');
    },

    downloadAllImages() {
      if (this.images.length === 0) {
        ElMessage.warning('没有可下载的街景图像');
        return;
      }
      this.images.forEach((image) => {
        const link = document.createElement('a');
        link.href = image.url;
        link.download = `streetview_${this.latitude}_${this.longitude}_${image.heading}.png`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
      ElMessage.success('开始下载街景图像');
    },
  },
};
</script>

<style scoped>
.search-box {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  box-sizing: border-box;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.input-group .el-input {
  width: 100%;
}

.input-group .el-button {
  margin-top: 10px;
  height: 30px;
  width: 50px;
  border-radius: 4px;
  align-items: center;
}

.image-display {
  margin-top: 20px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 12px;
}

.image-item {
  position: relative;
}

.street-view-image {
  width: 100%;
  height: 100px;
  object-fit: cover;
  border-radius: 6px;
  cursor: pointer;
  transition: transform 0.2s;
}

.street-view-image:hover {
  transform: scale(1.05);
}

.image-label {
  position: absolute;
  bottom: 8px;
  left: 8px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.download-btn {
  margin-top: 16px;
  width: 100%;
  height: 40px;
}

.no-image {
  margin-top: 24px;
  text-align: center;
  color: #666;
  font-size: 14px;
}
.button-group{
  display: flex;
  justify-content: center;
}
</style>
